home *** CD-ROM | disk | FTP | other *** search
/ Aminet 40 / Aminet 40 (2000)(Schatztruhe)[!][Dec 2000].iso / Aminet / dev / lang / Python16.lha / Python-1.6 / Lib / Python1.6 / locale.py < prev    next >
Encoding:
Python Source  |  2000-02-04  |  2.2 KB  |  78 lines

  1. """Support for number formatting using the current locale settings."""
  2.  
  3. # Author: Martin von Loewis
  4.  
  5. from _locale import *
  6. import string
  7.  
  8. #perform the grouping from right to left
  9. def _group(s):
  10.     conv=localeconv()
  11.     grouping=conv['grouping']
  12.     if not grouping:return s
  13.     result=""
  14.     while s and grouping:
  15.         # if grouping is -1, we are done 
  16.         if grouping[0]==CHAR_MAX:
  17.             break
  18.         # 0: re-use last group ad infinitum
  19.         elif grouping[0]!=0:
  20.             #process last group
  21.             group=grouping[0]
  22.             grouping=grouping[1:]
  23.         if result:
  24.             result=s[-group:]+conv['thousands_sep']+result
  25.         else:
  26.             result=s[-group:]
  27.         s=s[:-group]
  28.     if s and result:
  29.         result=s+conv['thousands_sep']+result
  30.     return result
  31.  
  32. def format(f,val,grouping=0):
  33.     """Formats a value in the same way that the % formatting would use,
  34.     but takes the current locale into account. 
  35.     Grouping is applied if the third parameter is true."""
  36.     result = f % val
  37.     fields = string.splitfields(result,".")
  38.     if grouping:
  39.         fields[0]=_group(fields[0])
  40.     if len(fields)==2:
  41.         return fields[0]+localeconv()['decimal_point']+fields[1]
  42.     elif len(fields)==1:
  43.         return fields[0]
  44.     else:
  45.         raise Error,"Too many decimal points in result string"
  46.     
  47. def str(val):
  48.     """Convert float to integer, taking the locale into account."""
  49.     return format("%.12g",val)
  50.  
  51. def atof(str,func=string.atof):
  52.     "Parses a string as a float according to the locale settings."
  53.     #First, get rid of the grouping
  54.     s=string.splitfields(str,localeconv()['thousands_sep'])
  55.     str=string.join(s,"")
  56.     #next, replace the decimal point with a dot
  57.     s=string.splitfields(str,localeconv()['decimal_point'])
  58.     str=string.join(s,'.')
  59.     #finally, parse the string
  60.     return func(str)
  61.  
  62. def atoi(str):
  63.     "Converts a string to an integer according to the locale settings."
  64.     return atof(str,string.atoi)
  65.  
  66. def test():
  67.     setlocale(LC_ALL,"")
  68.     #do grouping
  69.     s1=format("%d",123456789,1)
  70.     print s1,"is",atoi(s1)
  71.     #standard formatting
  72.     s1=str(3.14)
  73.     print s1,"is",atof(s1)
  74.     
  75.  
  76. if __name__=='__main__':
  77.     test()
  78.